package org.particlethink.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.slf4j.SLF4JLogger;
import org.particlethink.mapper.ProjectUserMapper;
import org.particlethink.mapper.SupplierUserMapper;
import org.particlethink.model.ProjectUser;
import org.particlethink.model.SupplierUser;
import org.particlethink.model.User;
import org.particlethink.response.BaseResponse;
import org.particlethink.response.UserTokenAndRoleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserTokenHandler userTokenHandler;
    @Autowired
    private ProjectUserMapper projectUserMapper;
    @Autowired
    private SupplierUserMapper supplierUserMapper;
    private final static Logger logger = LoggerFactory.getLogger(TokenFilter.class);


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        DefaultUser defaultUser = ((DefaultUser) authentication.getPrincipal());
        User user = defaultUser.getUser();
        int role = 0;
        if (defaultUser.isProjectConsumer()) {
            role = 1;
        } else if (defaultUser.isSupplierConsumer()) {
            role = 2;
        }
        UserTokenAndRoleResponse userTokenAndRoleResponse = new UserTokenAndRoleResponse(userTokenHandler.handleUser(defaultUser), role, user.getUsername(), user.getPhone(), user.getUserType(), user.getDeptName(), user.getNickName(), user.getEmail());
        logger.debug("userTokenAndRoleResponse:{}", userTokenAndRoleResponse);


        response.getWriter().write(objectMapper.writeValueAsString(BaseResponse.success(userTokenAndRoleResponse)));


        if (defaultUser.isProjectConsumer()) {
            projectUserMapper.insertOrUpdate(new ProjectUser(user.getUserId(), user.getProjectIds().get(0), user.getUsername(), user.getPhone(), user.getNickName()));

        } else if (defaultUser.isSupplierConsumer()) {
            supplierUserMapper.insertOrUpdate(new SupplierUser(user.getUserId(), user.getSupplierIds().get(0), user.getUsername(), user.getPhone(), user.getNickName()));
        } else {

        }


    }
}
